package com.wenlin.myproduction.util;

import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.wenlin.myproduction.bean.GetVoiceResponse;
import com.wenlin.myproduction.widget.PadMediaPlayer;

import java.io.IOException;
import java.util.Vector;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Cookie;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * @author 文琳
 * @Email 377979485@qq.com
 * @desc
 * @time 2022-07-01 星期五 16:18
 */
public class AIUtil {
    private static final int HANDLE_GET_CODE = 0;
    private static final int HANDLE_COMMIT_CODE = 1;
    private static final int HANDLE_GET_MP3 = 2;
    private static OkHttpClient mOkHttpClient;
    private static CountDownTimer timer;
    private static int index;
    private Vector<Cookie> cookieStore = new Vector<>();
    private static Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            String text = (String) msg.obj;
            switch (msg.what) {
                case HANDLE_GET_CODE:
                    getCode(text);
                    break;
                case HANDLE_COMMIT_CODE:
                    index = 1;
                    commitCode(text);
                    break;
                case HANDLE_GET_MP3:
                    getMp3File(text);
                    break;
                default:
            }
        }
    };

    private static AIUtil instance;

    private AIUtil(){

    }

    public static AIUtil getInstance(){
        if (instance==null) {
            synchronized (AIUtil.class) {
                if (instance == null){
                    instance = new AIUtil();
                }
            }
        }
        return instance;
    }

    private static void init() {
        if (Checker.isNull(mOkHttpClient)) {
            mOkHttpClient = new OkHttpClient();
//            cookieStore.clear();
//            cookieStore = null;
//            cookieStore = new Vector<>();
        }

//        new Thread(() -> {
//            mOkHttpClient = new OkHttpClient.Builder()
//                    .cookieJar(new CookieJar() {
//                        @Override
//                        public void saveFromResponse(@NonNull HttpUrl url, @NonNull List<Cookie> cookies) {
//                            //保存cookie
//                            cookieStore.addAll(cookies);
//                        }
//
//                        @Override
//                        public List<Cookie> loadForRequest(@NonNull HttpUrl url) {
//                            //装入cookie
//                            ArrayList<Cookie> cookies = new ArrayList<>();
//                            String xxbCookies = currentAccount.getCookie();
//                            if (!TextUtils.isEmpty(xxbCookies)) {
//                                String[] arr;
//                                if (xxbCookies.contains("$")) {
//                                    arr = xxbCookies.split("$");
//                                } else {
//                                    arr = xxbCookies.split(";");
//                                }
//                                if (arr.length > 0) {
//                                    for (String anArr :
//                                            arr) {
//                                        String[] temp = anArr.split("=");
//                                        if (temp.length != 2) {
//                                            continue;
//                                        }
//                                        Cookie cookie = new Cookie.Builder()
//                                                .hostOnlyDomain(url.host())
//                                                .name(temp[0].trim()).value(temp[1].trim())
//                                                .build();
//                                        cookies.add(cookie);
//                                    }
//                                }
//                            }
//                            if (Checker.hasList(cookieStore))
//                                cookies.addAll(cookieStore);
//                            return cookies;
//                        }
//                    })
//                    .build();
//        }).start();
    }

    public static void getCode(String text) {
        Request request = new Request.Builder()
                .removeHeader("User-Agent")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36 SE 2.X MetaSr 1.0")
                .addHeader(":authority", "www.zaixianai.cn")
                .addHeader(":method", "GET")
                .addHeader(":path", "/js/home//tncode.php?t=0.024890377399562347")
                .addHeader(":scheme", "https")
                .addHeader("accept", "image/webp,image/apng,image/*,*/*;q=0.8")
                .addHeader("accept-encoding", "gzip, deflate, br")
                .addHeader("accept-language", "zh-CN,zh;q=0.9")
                .addHeader("origin", "https://www.zaixianai.cn")
                .addHeader("referer", "https://www.zaixianai.cn/voiceCompose")
                .addHeader("cookie", "Hm_lvt_d09fdf7e91f77cddf85908f081d4a3bc=1656662503,1656662830,1656668387; PHPSESSID=ia77vk48v1covvvsg21focu9un; verifyBoFan=0; XSRF-TOKEN=eyJpdiI6ImM5UjZwNDVCVUkrRkxVMzRNSzRtaHc9PSIsInZhbHVlIjoiaHhKSFBMNGhEZWJvWXlmcGowSjBLUkhIQjhSanlyUnA0RVNOVldxM0xqcnErZWozRHJHa3hpTUpyNlhQeXdybSIsIm1hYyI6IjY1YjcyNTU0Y2UwNmJhNzY3YzVhOTM1NTlkNmUyNDgxMjA2Mzc3ZGRhM2FiNmQ2N2MyNDFkYTA2ODQ2ODMwNzIifQ%3D%3D; laravel_session=eyJpdiI6ImhsOFwvZ0dnOTlmd2R5RVlacUZcL0t2UT09IiwidmFsdWUiOiJRWEUwSmxWYlJyVU1oXC9VY01SUjY3QlwvVzZ2aklyZW1vZGNWa05ocW5IRVF5aE9wTEZTbGZRWFROeVczS0xlWUgiLCJtYWMiOiJiYWMzZjE0ZTFlNzBhNGRhMGMxOWIwNDFmYTExYTIyMTU0NDJjNmMzNjM2NDZmMjFmY2U3MmQ2ODYxYzU2YTM4In0%3D; Hm_lpvt_d09fdf7e91f77cddf85908f081d4a3bc=1656674709")
                .addHeader("sec-fetch-dest", "image")
                .addHeader("sec-fetch-mode", "no-cors")
                .addHeader("sec-fetch-site", "same-origin")
                .url("https://www.zaixianai.cn/js/home//tncode.php?t=0.1040311314250475")
                .build();
        if (mOkHttpClient == null) mOkHttpClient = new OkHttpClient.Builder().build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                LogUtils.e(e.getMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                ResponseBody body = response.body();
                String str = "";
                if (Checker.notNull(body)) {
                    str = body.string();//请注意.string()这个方法只能用一次
                    LogUtils.e("getCode response=\n" + str);
//                    Base64Util.base64ToFile(str, "/code/code.png");
//                    Message msg = Message.obtain();
//                    msg.what = HANDLE_COMMIT_CODE;
//                    msg.obj = text;
//                    handler.sendMessage(msg);
                } else {
                    LogUtils.e("getCode response=空的");
                }
            }
        });
    }

    public static void commitCode(String text) {
        Request request = new Request.Builder()
                .removeHeader("User-Agent")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36 SE 2.X MetaSr 1.0")
                .addHeader(":authority", "www.zaixianai.cn")
                .addHeader(":method", "GET")
                .addHeader(":path", "/js/home/check.php?tn_r="+index)
                .addHeader(":scheme", "https")
                .addHeader("accept", "*/*")
//                .addHeader("accept-encoding", "gzip, deflate, br")
                .addHeader("accept-language", "zh-CN,zh;q=0.9")
                .addHeader("referer", "https://www.zaixianai.cn/voiceCompose")
                .addHeader("cookie", "Hm_lvt_d09fdf7e91f77cddf85908f081d4a3bc=1656662503,1656662830,1656668387; PHPSESSID=ia77vk48v1covvvsg21focu9un; verifyBoFan=0; XSRF-TOKEN=eyJpdiI6ImM5UjZwNDVCVUkrRkxVMzRNSzRtaHc9PSIsInZhbHVlIjoiaHhKSFBMNGhEZWJvWXlmcGowSjBLUkhIQjhSanlyUnA0RVNOVldxM0xqcnErZWozRHJHa3hpTUpyNlhQeXdybSIsIm1hYyI6IjY1YjcyNTU0Y2UwNmJhNzY3YzVhOTM1NTlkNmUyNDgxMjA2Mzc3ZGRhM2FiNmQ2N2MyNDFkYTA2ODQ2ODMwNzIifQ%3D%3D; laravel_session=eyJpdiI6ImhsOFwvZ0dnOTlmd2R5RVlacUZcL0t2UT09IiwidmFsdWUiOiJRWEUwSmxWYlJyVU1oXC9VY01SUjY3QlwvVzZ2aklyZW1vZGNWa05ocW5IRVF5aE9wTEZTbGZRWFROeVczS0xlWUgiLCJtYWMiOiJiYWMzZjE0ZTFlNzBhNGRhMGMxOWIwNDFmYTExYTIyMTU0NDJjNmMzNjM2NDZmMjFmY2U3MmQ2ODYxYzU2YTM4In0%3D; Hm_lpvt_d09fdf7e91f77cddf85908f081d4a3bc=1656674709")
                .addHeader("sec-fetch-dest", "empty")
                .addHeader("sec-fetch-mode", "cors")
                .addHeader("sec-fetch-site", "same-origin")
                .url("https://www.zaixianai.cn/js/home/check.php?tn_r=" + index)
                .build();
        if (mOkHttpClient == null) mOkHttpClient = new OkHttpClient.Builder().build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                LogUtils.e(e.getMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                ResponseBody body = response.body();
                String str = "";
                if (Checker.notNull(body)) {
                    str = body.string();//请注意.string()这个方法只能用一次
                    LogUtils.e("commitCode response=\n" + str + "\nindex=" + index);
                    if (str.contains("ok")) {
                        LogUtils.e("index=" + index);
                        Message msg = Message.obtain();
                        msg.what = HANDLE_GET_MP3;
                        msg.obj = text;
                        handler.sendMessage(msg);
                    } else if (str.contains("error") && index < 190) {
                        index += 1;
                        commitCode(text);
                    }
                } else {
                    LogUtils.e("commitCode response=空的");
                }
            }
        });
    }

    public static void getMp3File(String text) {
        RequestBody body = new FormBody.Builder()
                .add("2021", "Api_getVoice")
                .add("content", text)
                .add("volume", "50")
                .add("speech_rate", "0")
                .add("voice", "Aixia")
                .add("_token", "rdoGhTzVa2sJ3FyhD1DXVZmEdOdhnETtmQ1mwmWB")
                .build();
        Request request = new Request.Builder()
                .removeHeader("User-Agent")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36 SE 2.X MetaSr 1.0")
//                .addHeader(":authority", "www.zaixianai.cn")
//                .addHeader(":path", "/Api_getVoice?2021=Api_getVoice")
//                .addHeader(":scheme", "https")
//                .addHeader("origin", "https://www.zaixianai.cn")
//                .addHeader("referer", "https://www.zaixianai.cn/voiceCompose")
                .addHeader("cookie", "XSRF-TOKEN=eyJpdiI6Ikdvb0ZwVDhhUThUNnF0akZBQkZvdVE9PSIsInZhbHVlIjoib1JhekVldmUxXC90U1ViSlhOajVkUTNQMDk1MmtUOHZ5ck80OFYrM0RiY2w4eDhIb2l5TnpOTlN1VjNrM2dBV20iLCJtYWMiOiI2NTU1MWY3ZDNhNWQzZDJkNGJkZDlhNjM1MTU3NDkwYjY3OTJlMjY2NTk0NDQ3NDdhMjgyMWMyZjU2ODZkY2VkIn0%3D; laravel_session=eyJpdiI6InFtbURcLytjWFdcL2hVYTdxc01GU3E2Zz09IiwidmFsdWUiOiJONnZSaHU3d1wvSDdsclRObk9jZit3MEcwUmdMRVpubVU0bm1qQ01VcGRCUW5mNEY0ZGRrM2IzcFFHNWV4QzF2MiIsIm1hYyI6Ijc4M2JiMmExYWE3Njk4ZjAxZjFlN2EwZTBiYjdjN2Q3YjdiMTgzMzdjYzg1ZGU2OWU4YmE3ZjIzOTgwMDZkMDcifQ%3D%3D; Hm_lvt_d09fdf7e91f77cddf85908f081d4a3bc=1656662503,1656662830,1656668387; Hm_lpvt_d09fdf7e91f77cddf85908f081d4a3bc=1656668387; PHPSESSID=ia77vk48v1covvvsg21focu9un; verifyBoFan=1")
//                .addHeader("", "")
                .url("https://www.zaixianai.cn/Api_getVoice")
                .post(body)
                .build();
        if (mOkHttpClient == null) mOkHttpClient = new OkHttpClient.Builder().build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                LogUtils.e(e.getMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                ResponseBody body = response.body();
                String str = "";
                if (Checker.notNull(body)) {
                    str = body.string();//请注意.string()这个方法只能用一次
                    LogUtils.e("response=\n" + str);
                    if (Checker.hasWord(str)) {
                        GetVoiceResponse getVoiceResponse = new Gson().fromJson(str, GetVoiceResponse.class);
                        if (Checker.notNull(getVoiceResponse) && Checker.notNull(getVoiceResponse.getData())) {
                            String finalUrl = "https://www.zaixianai.cn/voice/" + getVoiceResponse.getData().getFile_name();
                            PadMediaPlayer padMediaPlayer = PadMediaPlayer.create();
                            padMediaPlayer.setSource(finalUrl, true);
                            padMediaPlayer.setLooping(false);
                        }
                    }
                } else {
                    LogUtils.e("response=空的");
                }
            }
        });
    }

    public static void getMp3(String text) {
        Message msg = Message.obtain();
        msg.what = HANDLE_GET_CODE;
        msg.obj = text;
        handler.sendMessage(msg);
    }

    public static void download(String url) {
        LogUtils.e("下载mp3");
        String finalUrl = "https://www.zaixianai.cn/voice/" + url;
        Request request = new Request.Builder()
                .removeHeader("User-Agent")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36 SE 2.X MetaSr 1.0")
                .addHeader("cookie", "XSRF-TOKEN=eyJpdiI6Ikdvb0ZwVDhhUThUNnF0akZBQkZvdVE9PSIsInZhbHVlIjoib1JhekVldmUxXC90U1ViSlhOajVkUTNQMDk1MmtUOHZ5ck80OFYrM0RiY2w4eDhIb2l5TnpOTlN1VjNrM2dBV20iLCJtYWMiOiI2NTU1MWY3ZDNhNWQzZDJkNGJkZDlhNjM1MTU3NDkwYjY3OTJlMjY2NTk0NDQ3NDdhMjgyMWMyZjU2ODZkY2VkIn0%3D; laravel_session=eyJpdiI6InFtbURcLytjWFdcL2hVYTdxc01GU3E2Zz09IiwidmFsdWUiOiJONnZSaHU3d1wvSDdsclRObk9jZit3MEcwUmdMRVpubVU0bm1qQ01VcGRCUW5mNEY0ZGRrM2IzcFFHNWV4QzF2MiIsIm1hYyI6Ijc4M2JiMmExYWE3Njk4ZjAxZjFlN2EwZTBiYjdjN2Q3YjdiMTgzMzdjYzg1ZGU2OWU4YmE3ZjIzOTgwMDZkMDcifQ%3D%3D; Hm_lvt_d09fdf7e91f77cddf85908f081d4a3bc=1656662503,1656662830,1656668387; Hm_lpvt_d09fdf7e91f77cddf85908f081d4a3bc=1656668387; PHPSESSID=ia77vk48v1covvvsg21focu9un; verifyBoFan=1")
                .url(finalUrl)
                .build();
        if (mOkHttpClient == null) mOkHttpClient = new OkHttpClient.Builder().build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                LogUtils.e(e.getMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                ResponseBody body = response.body();
                String str = "";
                if (Checker.notNull(body)) {
                    str = body.string();//请注意.string()这个方法只能用一次
                    LogUtils.e("response=" + str);
                } else {
                    LogUtils.e("response=空的");
                }
            }
        });

    }


}
